# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1531995252939': {  # 支付宝 1～1000
        'API_KEY': '305C83D477A25497D75FD04AAE941474',
        'gateway': 'http://118.31.213.87/api/post',
        'query_gateway': 'http://118.31.213.87/api/query',
    },
    '1532485399606': {  # witch 支付宝 1～1000
        'API_KEY': 'C9DF818734AD61009F56C7589548178A',
        'gateway': 'http://118.31.213.87/api/post',
        'query_gateway': 'http://118.31.213.87/api/query',
    },
    '1532583743086': {  # loki 支付宝 1～1000
        'API_KEY': '1471817AD4248D1F66F78A80C177CAD4',
        'gateway': 'http://118.31.213.87/api/post',
        'query_gateway': 'http://118.31.213.87/api/query',
    },
    '1532584373019': {  # zs 支付宝 1～1000
        'API_KEY': '4438CA6AD2D99E7F8167E7D4831E002E',
        'gateway': 'http://118.31.213.87/api/post',
        'query_gateway': 'http://118.31.213.87/api/query',
    },
    '1536326747725': {  # dwc 支付宝 10～1000
        'API_KEY': '313DAC355DD77CBE1ABE67D7C53E5D3E',
        'gateway': 'http://47.98.19.210/api/post',
        'query_gateway': 'http://47.98.19.210/api/query',
    },
    '1536631581975': {  # zs 支付宝 10～1000
        'API_KEY': '8CBB209B35871213A949C372FAF1A349',
        'gateway': 'http://47.98.19.210/api/post',
        'query_gateway': 'http://47.98.19.210/api/query',
    },
    '1536631532445': {  # witch 支付宝 10～1000
        'API_KEY': 'DB7794F7E4A1E8E73DA633940A54012E',
        'gateway': 'http://47.98.19.210/api/post',
        'query_gateway': 'http://47.98.19.210/api/query',
    },
    '1536631563190': {  # loki 支付宝 10～1000
        'API_KEY': '592DCCF90F4B796DA514907979ECB540',
        'gateway': 'http://47.98.19.210/api/post',
        'query_gateway': 'http://47.98.19.210/api/query',
    },
    '1538793096301': {  # dwc 支付宝 10～10000
        'API_KEY': '5B70EB4C566286A2FEEB05682AE88C0F',
        'gateway': 'http://101.37.190.170/api/post',
        'query_gateway': 'http://101.37.190.170/api/query',
    },
    '1538793134370': {  # witch 支付宝 10～10000
        'API_KEY': '5FF89E081B6A4D61453EEA54812BF8B1',
        'gateway': 'http://101.37.190.170/api/post',
        'query_gateway': 'http://101.37.190.170/api/query',
    },
    '1538793154742': {  # loki 支付宝 10～10000
        'API_KEY': '01BD67C4F9A81C6ECCF305DCD8060ACB',
        'gateway': 'http://101.37.190.170/api/post',
        'query_gateway': 'http://101.37.190.170/api/query',
    },
    '1538793178460': {  # zs 支付宝 10～10000
        'API_KEY': '088C9BEAFF213B890655B36D7F2C3AA2',
        'gateway': 'http://101.37.190.170/api/post',
        'query_gateway': 'http://101.37.190.170/api/query',
    },
    '1540880719026': {  # sp 支付宝3%（10---3000）D0结算
        'API_KEY': 'F1054024E78EE85CDE5728348D3ABECB',
        'gateway': 'http://zs004.tiyti.com/api/post',
        'query_gateway': 'http://zs004.tiyti.com/api/query',
    },
    '1543812563946': {  # zs 支付宝 10～10000
        'API_KEY': '56374B2B154C367DB82DD1CD1FBEF8C3',
        'gateway': 'http://106.15.94.46:8080/api/post',
        'query_gateway': 'http://106.15.94.46:8080/api/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.sha1()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


# sha1(uid+pay_type+pay_id
# +group_id+goods_name+order_id+price+ notify_url+ exact+ sign_type+token)
# 转换为小写
def generate_sign(d, key):
    s = d['uid'] + d['pay_type'] + d['group_id'] \
        + d['goods_name'] + d['order_id'] + d['price'] + d['notify_url'] + d['exact'] + d['sign_type'] + key
    _LOGGER.info("zhipay sign str: %s", s)
    return _gen_sign(s)


# sha1(oid+uid+pay_type+pay_id
# +order_id+real_price+repeat+ sign_type+token)
def generate_notify_sign(d, key):
    s = d['oid'] + d['uid'] + d['pay_type'] + d['pay_id'] + d['order_id'] \
        + d['real_price'] + d['repeat'] + d['sign_type'] + key
    _LOGGER.info("zhipay notify sign str: %s", s)
    return _gen_sign(s)


# sha1(uid+order_id+salt+ sign_type+token)
def generate_query_sign(d, key):
    s = d['uid'] + d['order_id'] + d['salt'] + d['sign_type'] + key
    _LOGGER.info("zhipay query sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("zhipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 必填： 1.微信  2.支付宝  3.QQ钱包
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '1'
    elif service == 'alipay':
        payType = '2'
    elif service == 'qq':
        payType = '3'
    else:
        payType = '2'
    return payType


def _get_group_id_type(app_id):
    if app_id == '1543812563946':
        return ''
    return '0'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('uid', app_id),
        ('pay_type', _get_pay_type(service)),
        ('pay_id', ''),
        ('group_id', _get_group_id_type(app_id)),
        ('goods_name', 'charge'),
        ('order_id', str(pay.id)),
        ('price', str(pay_amount)),
        ('notify_url', '{}/pay/api/{}/zhipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('exact', 'true'),
        ('sign_type', 'sha1'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("zhipay create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("zhipay create rsp : %s", response.text)
    return {'charge_info': json.loads(response.text)['qrcode']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("zhipay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("zhipay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('zhipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    total_fee = float(data['real_price'])

    check_channel_order(pay_id, total_fee, app_id)

    query_charge(pay, app_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    pay_id = pay_order.id
    parameter_dict = OrderedDict((
        ('uid', app_id),
        ('order_id', str(pay_order.id)),
        ('salt', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())),
        ('sign_type', 'sha1'),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('zhipay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('zhipay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['status'])
        total_fee = float(data['real_price'])
        trade_no = data['oid']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 订单状态：0 未支付  1 支付完成  4 失败
        if trade_status == '1':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('zhipay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
